<?php

declare(strict_types=1);

namespace App\Controller\share;

use App\Common\Common;
use App\Common\User;
use App\Controller\AbstractController;
use Hyperf\Context\Context;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\AutoController;
use Swoole\Coroutine\Channel;
use function Hyperf\Coroutine\co;
use function Hyperf\Support\today;

#[AutoController(prefix: "share.share")]
class ShareController extends AbstractController
{
    /**
     * 分享页面控制台数据
     * @param Request $request
     * @return null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function painel(){
        $param = $this->request->all();
        $validator = $this->validatorFactory->make(
            $param,
            [
                'uid' => 'required',
            ],
            [
                'uid.required' => 'uid is required',
            ]
        );
        if ($validator->fails()) {
            $errorMessage = $validator->errors()->first();
            $this->logger->error("分享页面数据验证失败===>".$errorMessage);
            return $this->ReturnJson->failFul(219,[]);
        }

        $day_time = strtotime('today');

        $channel = new Channel();
        $data = co(function () use ($param, $day_time, $channel) {
            if (!isset($param['skin_type'])){
                $skin_type = 1;
            }else{
                $skin_type = $param['skin_type'];
            }

            try {
                //今日数据
                $day_user = Db::table('teamlevel')
                    ->where('puid', $param['uid'])
                    ->where('level', '<>', 0)
                    ->where('createtime', '>', $day_time)
                    ->pluck('uid')->toArray();
                //            ->toRawSql();

                $all_user = Db::table('teamlevel')
                    ->where('puid', $param['uid'])
                    ->where('level', '<>', 0)
                    ->pluck('uid')->toArray();

                $cz_num = Db::table('user_day_' . date('Ymd'))
                    ->whereIn('uid', $all_user)
                    ->where('total_pay_score', '>', 0)
                    ->count();

                $bet = Db::table('user_day_' . date('Ymd'))
                    ->whereIn('uid', $all_user)
                    ->where(function ($que){
                        $que->where('total_cash_water_score', '>', 0)
                            ->orWhere('total_bonus_water_score', '>', 0);
                    })
//                    ->where('total_cash_water_score', '>', 0)
//                    ->orWhere('total_bonus_water_score', '>', 0)
                    ->select(DB::raw('IFNULL(SUM(total_cash_water_score),0) as total_cash_water_score'),
                        DB::raw('IFNULL(SUM(total_bonus_water_score),0) as total_bonus_water_score'),
                        DB::raw('COUNT(uid) AS bet_num'))
                    ->first();
//                    ->toRawSql();
                //var_dump($bet);

                //$commission_day = Db::table('commission_day')->where('uid', $param['uid'])->whereDate('date', today())->first();
                $time = strtotime(date('Y-m-d'));
                $commission_day = Db::table('commission_log')
                    ->where('puid', $param['uid'])
                    ->where('createtime', '>=', $time)
                    ->selectRaw('IFNULL(SUM(commission),0) as commission')
                    ->first();

                //总数据
                $order = Db::table('order')->whereIn('uid', $all_user)->where('pay_status', 1)->groupBy('uid')->pluck('uid');
                $userinfo = Db::table('userinfo')
                    ->whereIn('uid', $all_user)
                    ->select(DB::raw('IFNULL(SUM(total_cash_water_score),0) as total_cash_water_score'),
                        DB::raw('IFNULL(SUM(total_bonus_water_score),0) as total_bonus_water_score'))
                    ->first();
                //$commission = Db::table('commission_day')->where('uid', $param['uid'])->select(DB::raw('IFNULL(SUM(commission),0) as commission'))->first();
                $commission = Db::table('commission_log')
                    ->where('puid', $param['uid'])
                    ->selectRaw('IFNULL(SUM(commission),0) as commission')
                    ->first();

                //领取的佣金
                $get_commission = Db::table('userinfo as a')
                    ->leftJoin('user_water as b','a.uid','=','b.uid')
                    ->where('a.uid', $param['uid'])->select('a.commission_total', 'a.commission','b.total_cash_water_score','b.total_bonus_water_score')->first();
                $bill_list = Db::table('commission_bill')->get()->toArray();
                $team_water = $get_commission['total_cash_water_score']>=0 && $get_commission['total_bonus_water_score']>=0 ? bcadd((string)$get_commission['total_cash_water_score'], (string)$get_commission['total_bonus_water_score']) : 0;
                //返利比例
                //$bill = 0;
                $bill_level = 1;
                foreach ($bill_list as $kk=>$item) {
                    if ($item['total_amount'] > $team_water) {
                        //$bill = bcdiv($bill_list[$kk-1]['bili'],10000,4);
                        $bill_level = $bill_list[$kk-1]['id'];
                        break;
                    }
                }

                $data = [];
                $data['Hoje']['register'] = count($day_user);
                $data['Hoje']['topup'] = $cz_num;
                $data['Hoje']['bet_money'] = !empty($bet) ? (int)bcadd((string)$bet['total_cash_water_score'], (string)$bet['total_bonus_water_score']) : 0;
                $data['Hoje']['bet_num'] = !empty($bet) ? $bet['bet_num'] : 0;
                $data['Hoje']['commission'] = !empty($commission_day) ? (int)$commission_day['commission'] : 0;

                $data['Total']['register'] = count($all_user);
                $data['Total']['topup'] = count($order);
                $data['Total']['bet_money'] = !empty($userinfo) ? (int)bcadd((string)$userinfo['total_cash_water_score'], (string)$userinfo['total_bonus_water_score']) : 0;
                $data['Total']['commission'] = !empty($commission) ? (int)$commission['commission'] : 0;

                $data['Comissao']['commission_total'] = !empty($get_commission) ? $get_commission['commission_total'] : 0;
                $data['Comissao']['commission'] = !empty($get_commission) ? $get_commission['commission'] : 0;
                $data['Comissao']['bill_level'] = $bill_level;

                //分享链接域名
                if ($skin_type == 1){
                    $data['share']['host'] = Common::getConfigValue('share_3377_url');
                }elseif ($skin_type == 2){
                    $data['share']['host'] = Common::getConfigValue('share_1699_url');
                }elseif ($skin_type == 3){
                    $data['share']['host'] = Common::getConfigValue('share_3_url');
                }elseif ($skin_type == 4){
                    $data['share']['host'] = Common::getConfigValue('share_4_url');
                }else{
                    $data['share']['host'] = Common::getConfigValue('share_3377_url');
                }

                $channel->push(json_encode($data));
            } catch (\Throwable $e) {
                // 捕获异常并处理
                $this->logger->error('分享页面数据获取错误:' . $e->getMessage());
                $channel->push('');
            }
        });

        $data = json_decode($channel->pop(),true);
        if ($data) {
            return $this->ReturnJson->successFul(200, $data, 1);
        }else{
            return $this->ReturnJson->successFul(200, [], 1);
        }
    }


    /**
     * 领取佣金
     * @param Request $request
     * @return null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getCommission(){
        $param = $this->request->all();
        $validator = $this->validatorFactory->make(
            $param,
            [
                'uid' => 'required',
            ],
            [
                'uid.required' => 'uid is required',
            ]
        );
        if ($validator->fails()) {
            $errorMessage = $validator->errors()->first();
            $this->logger->error("领取佣金数据验证失败===>".$errorMessage);
            return $this->ReturnJson->failFul(219,[]);
        }

        $userinfo = Db::table('userinfo')->where('uid',$param['uid'])->select('commission_total','commission')->first();
        if (empty($userinfo) || $userinfo['commission'] <= 0) return $this->ReturnJson->failFul(226);

        try {
            Db::beginTransaction();

            Db::table('commission_get')->insert([
                'uid' => $param['uid'],
                'commission' => $userinfo['commission'],
                'createtime' => time(),
            ]);

            Db::table('userinfo')->where('uid',$param['uid'])->update([
                'commission_total' => Db::raw('commission_total + '.$userinfo['commission']),
                'commission' => 0
            ]);
            User::userEditCoin($param['uid'], $userinfo['commission'], 9, '领取下级返佣', 4, 9);
            User::editUserTotalGiveScore($param['uid'], $userinfo['commission']);
            Db::commit();
            return $this->ReturnJson->successFul(200,[],1);

        }catch (\Throwable $e){
            Db::rollback();
            $this->logger->error("错误文件===" . $e->getFile() . '===错误行数===' . $e->getLine() . '===错误信息===' . $e->getMessage());
            return $this->ReturnJson->failFul();
        }
    }

    /**
     * 佣金领取记录
     * @param Request $request
     * @return mixed
     */
    public function commissionGetList(){
        $param = $this->request->all();
        $validator = $this->validatorFactory->make(
            $param,
            [
                'uid' => 'required',
            ],
            [
                'uid.required' => 'uid is required',
            ]
        );
        if ($validator->fails()) {
            $errorMessage = $validator->errors()->first();
            $this->logger->error("佣金记录数据验证失败===>".$errorMessage);
            return $this->ReturnJson->failFul(219,[]);
        }

        $limit = isset($param['page_size']) ? $param['page_size'] : 30;

        $list = Db::table('commission_get')
            ->where('uid',$param['uid'])
            ->orderBy('createtime','desc')
            ->paginate((int)$limit);
        $data = [];
        $data['list'] = $list->items();
        $data['totalNum'] = $list->total();
        return $this->ReturnJson->successFul(200,$data,1);
    }

    /**
     * 下级用户列表
     * @param Request $request
     * @return null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function junior(){
        $param = $this->request->all();
        $validator = $this->validatorFactory->make(
            $param,
            [
                'uid' => 'required',
            ],
            [
                'uid.required' => 'uid is required',
            ]
        );
        if ($validator->fails()) {
            $errorMessage = $validator->errors()->first();
            $this->logger->error("分享下级数据验证失败===>".$errorMessage);
            return $this->ReturnJson->failFul(219,[]);
        }

        $limit = isset($param['page_size']) ? $param['page_size'] : 30;

        $where = [];
        $zwhere = [];
        if (isset($param['date']) && !empty($param['date'])){
            $time = strtotime($param['date']);
            $end_time = $time + 86400;
            $where[] = ['c.createtime','<',$end_time];
            $where[] = ['c.createtime','>=',$time];
            $zwhere[] = ['createtime','<',$end_time];
            $zwhere[] = ['createtime','>=',$time];
        }

        /*$teamlevel = Db::table('teamlevel as a')
            ->leftJoin('userinfo as b','a.uid','=','b.uid')
            ->leftJoin('commissionlog as c','a.uid','=','c.uid')
            ->where(['a.puid' => $param['uid'], 'a.level' => 1])
            ->where($where)
            ->selectRaw('br_a.uid,IFNULL(br_b.total_cash_water_score,0) as total_cash_water_score,IFNULL(br_b.total_bonus_water_score,0) as total_bonus_water_score,
            IFNULL(SUM(br_c.commission_money),0) AS team_bet,COUNT(DISTINCT br_c.char_uid) as num,IFNULL(GROUP_CONCAT(DISTINCT br_c.char_uid),"") as xj_users')
            ->groupBy('a.uid')
            ->orderBy('a.createtime','desc')
            ->paginate((int)$limit);*/
        $teamlevel = Db::table('teamlevel as a')
            ->leftJoin('userinfo as b','a.uid','=','b.uid')
            ->leftJoin('commission_log as c','a.puid','=','c.puid')
            ->where(['a.puid' => $param['uid'], 'a.level' => 1])
            ->where($where)
            ->selectRaw('br_a.uid,IFNULL(br_b.total_cash_water_score,0) as total_cash_water_score,IFNULL(br_b.total_bonus_water_score,0) as total_bonus_water_score')
            //IFNULL(SUM(br_c.BetAmount),0) AS team_bet,COUNT(DISTINCT br_c.uid) as num,IFNULL(SUM(br_c.commission),0) AS commission,
            //            IFNULL(GROUP_CONCAT(DISTINCT br_c.uid),"") as xj_users
            ->groupBy('a.uid')
            ->orderBy('a.createtime','desc')
            ->paginate((int)$limit);
//            ->toRawSql();
//        var_dump($teamlevel);
        $teamlevels = $teamlevel->items();
        //var_dump($teamlevels);

        $all_bet = 0;
        if (!empty($teamlevels)){
            foreach ($teamlevels as $key=>&$value){
                //直属返佣
                $commission_zs = Db::table('commission_log')->where('uid',$value['uid'])->where('puid',$param['uid'])
                    ->where($zwhere)
                    ->selectRaw('IFNULL(SUM(commission),0) AS commission,IFNULL(SUM(BetAmount),0) AS BetAmount,COUNT(DISTINCT uid) as num')->first();
                //var_dump($commission_zs);

                //返佣
                //$users_arr = explode(',',$value['xj_users']);
                //$users_arr[] = (string)$value['uid'];
                //$teamleve_xj_user = Db::table('teamlevel')->whereIn('puid',$users_arr)->where('level','>',0)->get('uid')->toArray();
                $teamleve_xj_user = Db::table('teamlevel')->where('puid',$value['uid'])->where('level','>',0)->get('uid')->toArray();
                $teamleve_xj_arr = array_column($teamleve_xj_user,'uid');
                //var_dump($teamleve_xj_arr);

                $commission = Db::table('commission_log')->whereIn('uid',$teamleve_xj_arr)
                    ->where($zwhere)
                    ->selectRaw('IFNULL(SUM(commission),0) AS commission,IFNULL(SUM(BetAmount),0) AS team_bet,
                    COUNT(DISTINCT uid) as num')->first();
                //$all_bet = $all_bet + $commission_zs['BetAmount'];// + $value['team_bet']

                $value['commission'] = $commission['commission'] + $commission_zs['commission']; //$value['commission'] +
                $value['team_bet'] = $commission['team_bet']; //$value['team_bet'] +
//                $value['bet'] = bcadd((string)$value['total_cash_water_score'], (string)$value['total_bonus_water_score']);
                $value['bet'] = $commission_zs['BetAmount'];
                $value['num'] = $commission['num']; //+ $commission_zs['num']; $value['num'] +


                //$value['uid'] = $this->hideMiddle($value['uid']);

                unset($value['total_cash_water_score'],$value['total_bonus_water_score'],$value['xj_users']);
            }
        }

        $commission_all = Db::table('commission_log')->where('puid',$param['uid'])
            ->where($zwhere)
            ->selectRaw('IFNULL(SUM(BetAmount),0) AS team_bet')->first();
        $all_bet = $commission_all['team_bet'];

        $all_teamlevel = Db::table('teamlevel as a')
            ->leftJoin('commission_log as c','a.puid','=','c.puid')
            ->where(['a.puid' => $param['uid']])
            ->where('a.level','>',0)
            ->where($where)
            ->select('a.uid','a.level')
            ->groupBy('a.uid')
            ->get()->toArray();
        $level1 = [];
        $level2 = [];
        if (!empty($all_teamlevel)){
            foreach ($all_teamlevel as $ak=>$av){
                if ($av['level'] == 1){
                    $level1[] = $av['uid'];
                }else{
                    $level2[] = $av['uid'];
                }
            }
        }

        $level1_commission = Db::table('commission_log')->where('puid',$param['uid'])->whereIn('uid',$level1)
            ->where($zwhere)
            ->selectRaw('IFNULL(SUM(commission),0) AS really_money')->first();
        $level2_commission = Db::table('commission_log')->where('puid',$param['uid'])->whereIn('uid',$level2)
            ->where($zwhere)
            ->selectRaw('IFNULL(SUM(commission),0) AS really_money')->first();

        $data = [];
        $data['list'] = $teamlevels;
        $data['totalNum'] = $teamlevel->total();
        $data['total_direct_commission'] = bcadd((string)$level1_commission['really_money'],(string)$level2_commission['really_money']);
        $data['total_indirect_commission'] = $level2_commission['really_money'];
        //$data['all_bet'] = bcadd((string)$level1_commission['commission_money'],(string)$level2_commission['commission_money']);
        $data['all_bet'] = $all_bet;
        return $this->ReturnJson->successFul(200, $data, 1);
    }

    /**
     * 每日数据
     * @param Request $request
     * @return null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function dayData(){
        $param = $this->request->all();
        $validator = $this->validatorFactory->make(
            $param,
            [
                'uid' => 'required',
            ],
            [
                'uid.required' => 'uid is required',
            ]
        );
        if ($validator->fails()) {
            $errorMessage = $validator->errors()->first();
            $this->logger->error("分享每日数据验证失败===>".$errorMessage);
            return $this->ReturnJson->failFul(219,[]);
        }

        $limit = isset($param['page_size']) ? $param['page_size'] : 30;

        /*$list = Db::table('commission_day')
            ->where('uid',$param['uid'])
            ->orderBy('date','desc')
            ->paginate((int)$limit);*/
        $list = Db::table('commission_log')->where('puid',$param['uid'])
            ->selectRaw('DATE(FROM_UNIXTIME(createtime)) AS date,IFNULL(SUM(commission),0) AS commission,IFNULL(SUM(BetAmount),0) AS bet,COUNT(DISTINCT uid) as bet_num,
            MAX(bill_level) AS bill_level')
            ->groupBy('date')
            ->orderBy('date','desc')
            ->paginate((int)$limit);

        $list_data = $list->items();
        if (!empty($list_data)){
            foreach ($list_data as $key=>&$value){
                $level_time = strtotime($value['date']);
                $end_time = $level_time + 86400;
                $teamlevel = Db::table('teamlevel')
                    ->where('level','>',0)
                    ->where('puid',$param['uid'])
                    ->where('createtime','>=',$level_time)
                    ->where('createtime','<',$end_time)
                    ->count();
                $value['num'] = $teamlevel;
            }
        }

        $data = [];
        $data['list'] = $list_data;
        $data['totalNum'] = $list->total();
        return $this->ReturnJson->successFul(200,$data,1);

    }

    /**
     * 返佣比例
     * @return null
     */
    public function commissionBill()
    {
        $data = Db::table('commission_bill')->select('id as level','total_amount','bili')->get()->toArray();
        foreach ($data as &$itam){
            $itam['total_amount'] = $itam['total_amount']/1000000;
        }
        return $this->ReturnJson->successFul(200,$data,1);
    }


    /**
     * 隐藏字符中间几位
     * @param $str
     * @return array|string|string[]
     */
    function hideMiddle($str) {
        $hidden = substr_replace((string)$str,'****',2,3);

        return $hidden;
    }

    /**
     * 下级绑定上级
     * @return null
     */
    public function bindSuperior()
    {
        $param = $this->request->all();
        $validator = $this->validatorFactory->make(
            $param,
            [
                'uid' => 'required',
                'puid' => 'required',
            ],
            [
                'uid.required' => 'uid is required',
                'puid.required' => 'puid is required',
            ]
        );
        if ($validator->fails()) {
            $errorMessage = $validator->errors()->first();
            $this->logger->error("绑定上级验证失败===>".$errorMessage);
            return $this->ReturnJson->failFul(219,[]);
        }

        $share_strlog = Db::table('share_strlog as a')
            ->leftJoin('userinfo as b','a.uid','=','b.uid')
            ->select('a.phone','a.package_id','a.channel','a.appname','a.nickname','a.puid','a.avatar','b.coin')
            ->where('a.uid', $param['uid'])
            ->first();
        if (empty($share_strlog)) return $this->ReturnJson->failFul(226);
        if ($share_strlog['puid'] > 0){
            return $this->ReturnJson->failFul(290);
        }
        $p_share_strlog = Db::table('share_strlog')->where('uid',$param['puid'])->first();
        if (empty($p_share_strlog)) return $this->ReturnJson->failFul(291);

        try {
            Db::beginTransaction();

            //游戏层级表添加上级数据 ???
            $res = self::setTeamLevel2($param['uid'], $param['puid'], $share_strlog, 0, []); //团队数据处理
            if(!$res){
                Db::rollback();
                return $this->ReturnJson->failFul();
            }

            //添加代理团队数据
            $is_agent = 0;
            $agent = Db::table('agent')->select('uid','type','level')->where(['uid' => $param['puid']])->first();
            if (!empty($agent)) {
                $type = 0;
                if ($agent['type'] == 2) {
                    $type = 3;
                } elseif ($agent['type'] == 3) {
                    $type = 1;
                }
                $is_agent = Common::setTeamLevel($param['uid'], $param['puid'], $type, 0, $share_strlog, $agent['level'] + 1);
            }

            $res = Db::table('share_strlog')->where('uid', $param['uid'])->update(['is_agent_user' => 1,'puid'=> $param['puid'], 'agent' => $is_agent]);
            if(!$res){
                Db::rollback();
                return $this->ReturnJson->failFul();
            }
            $res = Db::table('userinfo')->where('uid', $param['uid'])->update(['puid'=> $param['puid']]);
            if(!$res){
                Db::rollback();
                return $this->ReturnJson->failFul();
            }



            Db::commit();
            return $this->ReturnJson->successFul(200,[],1);

        }catch (\Throwable $e){
            Db::rollback();
            $this->logger->error("错误文件===" . $e->getFile() . '===错误行数===' . $e->getLine() . '===错误信息===' . $e->getMessage());
            return $this->ReturnJson->failFul();
        }

    }

    /**
     * 设置用户团队层级数据
     * @param $uid 用户UID
     * @param $puid 上级代理用户UID
     * @param $level 上级用户层级 默认是自己 0
     * @return void
     */
    public static function setTeamLevel2($uid, $puid, $share_strlog=[], $level = 0, $param=[]){

        //第一次进来，如果有团队详细数据就直接返回。
        if(!$level){
            //$this->installTeamLevel2($uid,$uid,0);
            //存储团队信息
            if($puid > 0){
                //转盘邀请用户处理
                $turntable_id = 0;
                $money = 0;
                /*if (isset($param['turntable_id']) && $param['turntable_id'] > 0){
                    $turntable_id = $param['turntable_id'];
                    $turntable_user_count = Db::name('user_team')->where('turntable_id',$turntable_id)->count();
                    if ($turntable_user_count <= 5){
                        $money = mt_rand(5, 15) / 100;
                    }else{
                        $probability = 0.2;  // 控制概率，范围为 0 到 1 之间
                        $randomNumber = mt_rand(1, 100) / 100;  // 生成一个介于 0.01 和 1 之间的随机数
                        if ($randomNumber < $probability) {
                            $money = 0.01;
                        } else {
                            $money = 0;
                        }
                    }
                    Db::name('turntable')->where('id',$turntable_id)->inc('money',$money)->update();
                }*/

                Db::table('user_team')->insert([
                    'uid' => $uid,
                    'nickname' => $share_strlog['nickname'],
                    'avatar' => $share_strlog['avatar'],
                    'puid' => $puid,
                    'createtime' => time(),
                    'channel' => $share_strlog['channel'],
                    'package_id' => $share_strlog['package_id'],
                    'turntable_id' => $turntable_id,
                    'money' => $money,
                    'or_coin' => $share_strlog['coin'],
                ]);
            }else{
                return 1;
            }
        }

        //防止层级过多出问题，这里最多设置10级
        if($level >= 10)return 1;

        self::installTeamLevel2($uid,$puid,$level + 1);

        //获取上级用户是否还有上级用户
        $user_team = Db::table('user_team')->select('puid')->where('uid',$puid)->first();
        if(!$user_team)return 1;

        //如果推荐代理有上级用户，同时上级用户不是代理自己
        if($user_team['puid'] > 0 && $user_team['puid'] != $puid) self::setTeamLevel2($uid, $user_team['puid'], $share_strlog,$level + 1);
        return 1;
    }


    /**
     * 储存用户团队层级数据
     * @return void 存储
     */
    private static function installTeamLevel2($uid,$puid,$level = 0){
        Db::table('teamlevel')->insert([
            'uid' => $uid,
            'puid' => $puid,
            'level' => $level,
            'createtime' => time(),
        ]);
    }

    /**电销包专用 获取分享链接
     * @return null
     */
    public function getAgentShare()
    {
        $url = Common::getConfigValue('agent_host1');
        $data = [
            'host1' => $url
        ];
        return $this->ReturnJson->successFul(200,$data,1);
    }

    //---------------P77版本-----------------//

    /**
     * 分享落地页填写手机号
     * @return null
     */
    public function shareBefore()
    {
        $param = $this->request->all();
        $validator = $this->validatorFactory->make(
            $param,
            [
                'phone' => 'required',
                'puid' => 'required',
            ],
            [
                'phone.required' => 'phone is required',
                'puid.required' => 'puid is required',
            ]
        );
        if ($validator->fails()) {
            $errorMessage = $validator->errors()->first();
            $this->logger->error("分享落地页填写验证失败===>".$errorMessage);
            return $this->ReturnJson->failFul(219,[],2);
        }

        //是否填过
        $share_before = Db::table('share_before')->where('phone',$param['phone'])->first();
        if (!empty($share_before)){
            return $this->ReturnJson->failFul(221,[],2);
        }

        try {
            Db::beginTransaction();

            Db::table('share_before')->insert([
                'phone' => $param['phone'],
                'puid' => $param['puid'],
                'createtime' => time(),
            ]);


            Db::commit();
            return $this->ReturnJson->successFul(200,[],2);

        }catch (\Throwable $e){
            Db::rollback();
            $this->logger->error("错误文件===" . $e->getFile() . '===错误行数===' . $e->getLine() . '===错误信息===' . $e->getMessage());
            return $this->ReturnJson->failFul(201,[],2);
        }

    }

    public function myRewards()
    {
        $param = $this->request->all();
        $validator = $this->validatorFactory->make(
            $param,
            [
                'uid' => 'required',
            ],
            [
                'uid.required' => 'uid is required',
            ]
        );
        if ($validator->fails()) {
            $errorMessage = $validator->errors()->first();
            $this->logger->error("分享页面数据验证失败2===>".$errorMessage);
            return $this->ReturnJson->failFul(219,[]);
        }
        $uid = $param['uid'];
        if (!isset($param['skin_type'])){
            $skin_type = 1;
        }else{
            $skin_type = $param['skin_type'];
        }

        //下级数据
        $xj_user = Db::table('teamlevel')->where('puid',$uid)->whereIn('level',[1,2,3])->pluck('uid')->toArray();
        //$zs_user_yx = Db::table('user_team')->whereIn('uid', $zs_user)->where('pstatus',1)->pluck('uid')->toArray();
        $yx_bet = Db::table('userinfo')->whereIn('uid', $xj_user)->sum('total_cash_water_score');
        $member = count($xj_user);

        //等级列表
        $rule = Db::table('share_rule as a')
            ->leftJoin('teamlevel as b', function ($join) use ($uid){
                $join->on('a.level', '=', 'b.club_level')
                    ->where('b.uid', '=', $uid);
            })
            ->selectRaw('br_a.level,upgrade_member,upgrade_bet,max(rate1) rate1,max(first_deposit_rate) as first_deposit_rate,max(task_up) as task_up,IF(club_level IS NULL, 0, 1) AS is_my_level')
            ->groupBy('a.level')
            ->orderBy('a.level','asc')
            ->get()->toArray();
        if (!empty($rule)){
            foreach ($rule as $k=>$v){
                if ($v['is_my_level'] == 1){
                    $my_ldata = $v;
                    $my_ldata['key'] = $k;
                }
            }
        }
        //检测等级
        if (isset($my_ldata['upgrade_member']) && $member >= $my_ldata['upgrade_member'] && $yx_bet >= $my_ldata['upgrade_bet']){
            if (isset($rule[$my_ldata['key']+1])) { //有下一级时
                $rule[$my_ldata['key']]['is_my_level'] = 0;
                $rule[$my_ldata['key']+1]['is_my_level'] = 1;

                //修改等级
                Db::table('teamlevel')->where('uid',$uid)->where('level',0)->increment('club_level');
            }
        }


        //我的
        $userinfo = Db::table('userinfo')->where('uid',$uid)->selectRaw('commission_total,commission')->first();

        //今日返佣...
        $startOfDay = strtotime('today'); // 今日零点的时间戳
        $endOfDay = strtotime('tomorrow') - 1; // 今日 23:59:59 的时间戳
        $today_rewards = Db::table('commission_log')
            ->whereBetween('createtime', [$startOfDay, $endOfDay])
            ->sum('commission');


        //分享链接域名
        if ($skin_type == 1){
            $host = Common::getConfigValue('share_3377_url');
        }elseif ($skin_type == 2){
            $host = Common::getConfigValue('share_1699_url');
        }elseif ($skin_type == 3){
            $host = Common::getConfigValue('share_3_url');
        }elseif ($skin_type == 4){
            $host = Common::getConfigValue('share_4_url');
        }else{
            $host = Common::getConfigValue('share_3377_url');
        }
        //$host = '';

        $data = [];
        $data['member'] = $member;
        $data['bet'] = $yx_bet;
        $data['withdrawable'] = $userinfo['commission'];
        $data['total_rewards'] = $userinfo['commission_total'];
        $data['today_rewards'] = $today_rewards;
        $data['share_host'] = $host;
        $data['club_list'] = $rule;


        return $this->ReturnJson->successFul(200, $data, 1);

    }

    /**
     * 下属数据详情页
     * @return null
     */
    public function clubDetail()
    {
        $param = $this->request->all();
        $validator = $this->validatorFactory->make(
            $param,
            [
                'uid' => 'required',
                'tier' => 'required',
                'date' => 'required',
            ],
            [
                'uid.required' => 'uid is required',
                'tier.required' => 'tier is required',
                'date.required' => 'date is required',
            ]
        );
        if ($validator->fails()) {
            $errorMessage = $validator->errors()->first();
            $this->logger->error("团队详情数据验证失败===>".$errorMessage);
            return $this->ReturnJson->failFul(219,[]);
        }
        $uid = $param['uid'];
        $tier = $param['tier'];
        $date = strtotime($param['date']);
        $date_e = strtotime($param['date']) + 86399;

        $limit = isset($param['page_size']) ? $param['page_size'] : 30;

        $tier1 = 0;
        $tier2 = 0;
        $tier3 = 0;
        $club_level = 0;
        $yesterday_s = strtotime('yesterday');
        $today_s = strtotime('today');
        $today_e = strtotime('tomorrow') - 1; // 今日 23:59:59 的时间戳
        // 本月开始时间戳
        $monthStart = strtotime(date('Y-m-01 00:00:00'));
        // 本月结束时间戳
        $monthEnd = strtotime(date('Y-m-t 23:59:59'));
        $today_num = 0;
        $yesterday_num = 0;
        $month_num = 0;
        $tier_user1 = [];
        $tier_user2 = [];
        $tier_user3 = [];

        //所有下级
        $user_list = Db::table('teamlevel')->where('puid',$uid)->whereIn('level',[0,1,2,3])->get()->toArray();
        foreach ($user_list as $key=>$value){
            if ($value['level'] == 0){
                $club_level = $value['club_level'];
            }
            if ($value['level'] == 1){
                $tier1 += 1;
                $tier_user1[] = $value['uid'];
            }
            if ($value['level'] == 2){
                $tier2 += 1;
                $tier_user2[] = $value['uid'];
            }
            if ($value['level'] == 3){
                $tier3 += 1;
                $tier_user3[] = $value['uid'];
            }
            if ($value['createtime'] >= $today_s && $value['createtime'] <= $today_e){
                $today_num += 1;
            }
            if ($value['createtime'] >= $yesterday_s && $value['createtime'] < $today_s){
                $yesterday_num += 1;
            }
            if ($value['createtime'] >= $monthStart && $value['createtime'] <= $monthEnd){
                $month_num += 1;
            }

        }

        //返佣用户列表
        $wherein_user = [];
        if ($tier == 1){
            $wherein_user = $tier_user1;
        }elseif ($tier == 2){
            $wherein_user = $tier_user2;
        }elseif ($tier == 3){
            $wherein_user = $tier_user3;
        }
        $where = [];
        if (isset($param['search_uid']) && !empty($param['search_uid'])){
            $where = [['a.uid', '=', $param['search_uid']]];
        }
        $order = 'commission';
        $sort = 'desc';
        if (isset($param['commission']) && !empty($param['commission'])){
            if ($param['commission'] == 2){
                $sort = 'asc';
            }
        }
        if (isset($param['join']) && !empty($param['join'])){
            $order = 'a.createtime';
            if ($param['join'] == 2){
                $sort = 'asc';
            }else{
                $sort = 'desc';
            }
        }


        $list = Db::table('user_team as a')
            ->leftJoin('commission_log as b', function ($join) use ($date, $date_e){
                $join->on('a.uid', '=', 'b.uid')
                    ->whereBetween('b.createtime', [$date, $date_e]);
            })
            ->leftJoin('order as c', function ($join) use ($date, $date_e){
                $join->on('a.uid', '=', 'c.uid')
                    ->where('pay_status',1)
                    ->whereBetween('c.createtime', [$date, $date_e]);
            })
            ->where('a.createtime','<=', $date_e)
            ->whereIn('a.uid', $wherein_user)
            ->where($where)
            ->selectRaw("br_a.nickname,br_a.avatar,FROM_UNIXTIME(br_a.createtime,'%Y-%m-%d %H:%i:%s') as join_time,IFNULL(SUM(br_b.commission),0) as commission,
            IFNULL(SUM(br_c.price),0) as deposit")
            ->groupBy('a.uid')
            ->orderBy($order,$sort)
            ->paginate((int)$limit);
        $list = $list->items();
        if (!empty($list)){
            foreach ($list as $k=>$v){
                $list[$k]['avatar'] = Common::domain_name_path($v['avatar']);
            }
        }

        $data = [];
        $data['club_stars'] = $club_level;
        $data['total_number'] = count($user_list) - 1;
        $data['today'] = $today_num;
        $data['yesterday'] = $yesterday_num;
        $data['month'] = $month_num;
        $data['tier1'] = $tier1;
        $data['tier2'] = $tier2;
        $data['tier3'] = $tier3;
        $data['list'] = $list;

        return $this->ReturnJson->successFul(200, $data, 1);
    }

    /**
     * 返佣详情列表
     * @return null
     */
    public function rewardsDetail()
    {
        $param = $this->request->all();
        $validator = $this->validatorFactory->make(
            $param,
            [
                'uid' => 'required',
                'type' => 'required', //0-all 1-bet 2-deposit 3-invite 4-inviteTask
                'date' => 'required',
            ],
            [
                'uid.required' => 'uid is required',
                'type.required' => 'type is required',
                'date.required' => 'date is required',
            ]
        );
        if ($validator->fails()) {
            $errorMessage = $validator->errors()->first();
            $this->logger->error("返佣详情数据验证失败===>".$errorMessage);
            return $this->ReturnJson->failFul(219,[]);
        }
        $uid = $param['uid'];
        $type = $param['type'];
        $date = $param['date'];
        $startOfMonth = strtotime("$date-01 00:00:00");
        $endOfMonth = strtotime(date('Y-m-t 23:59:59', $startOfMonth));
        $limit = isset($param['page_size']) ? $param['page_size'] : 30;

        //所有下级
        $user_arr = Db::table('teamlevel')->where('puid',$uid)->whereIn('level',[0,1,2,3])->pluck('uid')->toArray();

        if ($type == 0){
            $list = Db::table('commission_log')
                ->whereIn('uid', $user_arr)
                ->selectRaw('FROM_UNIXTIME(createtime, "%Y-%m-%d") as time, IFNULL(SUM(commission),0) as commission,1 as state,uid,BetAmount as num')
                ->whereBetween('createtime', [$startOfMonth, $endOfMonth])
                ->groupBy('time') // 按天分组
                ->orderBy('time', 'desc') // 按天排序
                ->paginate((int)$limit);
            $list = $list->items();

            //总返佣
            $total_commission = Db::table('commission_log')
                ->whereIn('uid', $user_arr)
                ->sum('commission');
        }else{
            $list = Db::table('commission_log')
                ->whereIn('uid', $user_arr)
                ->where('dataType', $type)
                ->selectRaw('FROM_UNIXTIME(createtime, "%Y-%m-%d") as time, IFNULL(SUM(commission),0) as commission,1 as state,uid,BetAmount as num')
                ->whereBetween('createtime', [$startOfMonth, $endOfMonth])
                ->groupBy('uid','time') // 按天分组
                ->orderBy('time', 'desc') // 按天排序
                ->paginate((int)$limit);
            $list = $list->items();

            //总返佣
            $total_commission = Db::table('commission_log')
                ->whereIn('uid', $user_arr)
                ->where('dataType', $type)
                ->sum('commission');
        }



        $data = [];
        $data['total_commission'] = $total_commission;
        $data['list'] = $list;

        return $this->ReturnJson->successFul(200, $data, 1);
    }

    /**
     * 邀请详情
     * @return null
     */
    public function inviteRewards()
    {
        $param = $this->request->all();
        $validator = $this->validatorFactory->make(
            $param,
            [
                'uid' => 'required',
            ],
            [
                'uid.required' => 'uid is required',
            ]
        );
        if ($validator->fails()) {
            $errorMessage = $validator->errors()->first();
            $this->logger->error("邀请返佣数据验证失败===>".$errorMessage);
            return $this->ReturnJson->failFul(219,[]);
        }
        $uid = $param['uid'];
        $today_s = strtotime('today');
        $today_e = strtotime('tomorrow') - 1; // 今日 23:59:59 的时间戳

        //所有下级
        $user_arr = Db::table('teamlevel')->where('puid',$uid)->whereIn('level',[1,2,3])->pluck('uid')->toArray();
        $team_user = Db::table('user_team')->where('pstatus',1)->whereIn('uid',$user_arr)
            ->selectRaw('uid,createtime')
            ->get()->toArray();//有效用户
        $yx_users = [];
        $new_user_num = 0;
        if (!empty($team_user)){
            $yx_users = array_column($team_user, 'uid');
            foreach ($team_user as $key=>$value){
                if ($value['createtime'] >= $today_s && $value['createtime'] <= $today_e){
                    $new_user_num += 1;
                }
            }
        }
        $commission = Db::table('commission_log')
            ->where('dataType',3)->whereIn('uid',$yx_users)->where('puid', $uid)
            ->sum('commission');

        //配置参数
        $share_config = Common::getMore('share_get_cash,share_get_cash_new,share_dayget_num');

        //任务数据
        $share_task = Db::table('share_task')->get()->toArray();


        $data = [];
        $data['total_rewards'] = $commission;
        $data['invites'] = count($user_arr);
        $data['total_invites'] = count($yx_users);
        $data['customer_get'] = $share_config['share_get_cash'];
        $data['friends_get'] = $share_config['share_get_cash_new'];
        $data['day_new_user'] = $new_user_num;
        $data['day_limit'] = $share_config['share_dayget_num'];
        $data['task_list'] = $share_task;

        return $this->ReturnJson->successFul(200, $data, 1);
    }

}
